package com.szrt.shiro;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

public class FirstShiro {

	@Test
	public void testName() throws Exception {
		//1.加载配置文件
	    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:test.ini");
	    //2.获取安全管理器  拿到一个实例
	    SecurityManager securitymanager=factory.getInstance();

	    //3.使安全管理器在整个jvm生效
	    SecurityUtils.setSecurityManager(securitymanager);

	    
	    Subject currentUser = SecurityUtils.getSubject();
	    
	    /*Session session = currentUser.getSession();*/
	    
	    AuthenticationToken token=new UsernamePasswordToken("bb", "11");
	    try {
	    	currentUser.login( token );
	    	System.out.println("登陆成功");
	    	    //无异常，说明就是我们想要的!
	    	}
	    catch ( UnknownAccountException uae ) {
	        //username 不存在，给个错误提示?
	    	System.out.println("用户名不存在");
	    } catch ( IncorrectCredentialsException ice ) {
	        //password 不匹配，再输入?
	    	System.out.println("密码不正解");
	    } catch ( LockedAccountException lae ) {
	        //账号锁住了，不能登入。给个提示?
	    	System.out.println("密码输入超过5次，请稍后再试~");
	    } 
	    catch (  AuthenticationException e) {
    	    //username 不存在，给个错误提示?
    		System.out.println("登陆失败");
    	}

	    Session session = currentUser.getSession();
	    session.setAttribute( "username", "bb2" );
	    System.out.println("username="+session.getAttribute("username"));
	    
	    //获得session （页面的用户名）
	    System.out.println("当前登陆人"+currentUser.getPrincipal());
	    
	    //返回trueORfalse  当前登陆人是否有admin角色
	    System.out.println("当前登陆人是否有admin角色"+currentUser.hasRole("admin"));
	    
	    // 当前登陆人是否有admin角色   返回trueORfalse 
	    System.out.println(currentUser.hasRole("guest"));
	    
	    // 当前登陆人是否有user:init角色   返回trueORfalse 
	    System.out.println(currentUser.isPermitted("user:init"));
	    
	    System.out.println("当前登陆人是否有guest:init角色 "+currentUser.isPermitted("guest:init"));
	    
	    //退出登陆 注销  session
	    currentUser.logout();
	    System.out.println("当前登陆人"+currentUser.getPrincipal());
	    
	    System.exit(0);
	  
	    
	}
}
